package com.hmall.order.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmall.common.client.SearchClient;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.impl.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

/**
 * TODO
 *
 * @Author mr.ma
 * @Date 2024/11/22 16:08
 */
@Component
@EnableScheduling
public class StockTask {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private SearchClient searchClient;


    @Scheduled(cron = "0 * * * *?")
    public void scheduleTask(){
        List<Order> list = orderService.lambdaQuery().eq(Order::getStatus, 1).list();
        if(list!=null && list.size()>0){
            for (Order order : list) {
                Date createTime = order.getCreateTime();
                LocalDateTime localDateTime = createTime.toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime();
                if(localDateTime.plus(30, ChronoUnit.MINUTES).isBefore(LocalDateTime.now())){
                    //条件成立，说明超过30分钟未支付 订单状态改变 并回复库存删减
                    orderService.lambdaUpdate().eq(Order::getId,order.getId())
                            .set(Order::getStatus,5).update();
                    LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(OrderDetail::getOrderId,order.getId());
                    OrderDetail orderDetail = orderDetailMapper.selectOne(queryWrapper);
                    Integer num = orderDetail.getNum();

                    searchClient.changes1(orderDetail.getItemId(),orderDetail.getNum());

                }
            }
        }
    }
}
